package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.jaya.budan.R;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.base.MyApplication;
import com.jaya.budan.bean.User_Limit;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.Circle_ImageView;
import com.jaya.budan.views.CommonPopWindow;
import com.jaya.budan.views.HorizontalListView;
import com.jaya.budan.views.MyListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.android.utils.Logger;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.wechat.WechatMoments;
import cn.jiguang.share.weibo.SinaWeiboMessage;

public class Topic_Detail_Activity extends BaseActivity implements View.OnClickListener, CommonPopWindow.ViewClickListener {

    private RelativeLayout back;
    private LinearLayout ll_topic_detail;
    private String access_token;
    private TextView tv_topic_name;
    private ImageView iv_topic_share;
    private User_Limit user_limit;
    private HorizontalListView main_hlv;
    private MyListView main_listview;
    private Circle_ImageView iv_geren_main_header;
    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String toastMsg = (String) msg.obj;
            ToolUtils.showToast(Topic_Detail_Activity.this, toastMsg);
        }
    };
    private PlatActionListener mPlatActionListener = new PlatActionListener() {
        @Override
        public void onComplete(Platform platform, int action, HashMap<String, Object> data) {
            if(handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享成功";
                handler.sendMessage(message);
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            if(handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享失败:" + (error != null ? error.getMessage() : "") + "---" + errorCode;
                Logger.dd("geren",message.obj+"");
                handler.sendMessage(message);
            }
        }

        @Override
        public void onCancel(Platform platform, int action) {
            if(handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享取消";
                handler.sendMessage(message);
            }
        }
    };

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic_detail);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        user_limit = (User_Limit) intent.getSerializableExtra("user_limit");
        Log.d("topic_main", JSON.toJSONString(user_limit));
        back = findViewById(R.id.back);
        main_hlv = findViewById(R.id.main_hlv);
        ll_topic_detail = findViewById(R.id.ll_topic_detail);
        main_listview = findViewById(R.id.main_listview);
        iv_geren_main_header = findViewById(R.id.iv_geren_main_header);
        tv_topic_name = findViewById(R.id.tv_topic_name);
        iv_topic_share = findViewById(R.id.iv_topic_share);
        back.setOnClickListener(this);
        iv_topic_share.setOnClickListener(this);
        tv_topic_name.setText("" + user_limit.getName());
        Glide.with(this).load(user_limit.getImage()).apply(new RequestOptions()
                .placeholder(R.mipmap.iv_main_item).error(R.mipmap.iv_main_item)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//关闭Glide的硬盘缓存机制
        ).into(iv_geren_main_header);
        SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                ll_topic_detail.setBackground(resource);
            }
        };
        Glide.with(this).load(user_limit.getImage()).apply(new RequestOptions()
                .placeholder(R.mipmap.banner).error(R.mipmap.banner)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//关闭Glide的硬盘缓存机制
        ).into(simpleTarget);
        // 获取屏幕宽高
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽（像素，如：480px）
//        main_hlv.setAdapter(new VIP_ZX_HorizontalListViewAdapter(Topic_Detail_Activity.this, screenWidth, null, null, 5, vip_jiLu, null));
//        main_listview.setAdapter();
        main_hlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_about_us_pingjia:
                Intent intent = new Intent(Topic_Detail_Activity.this, Privacy_WebView_Activity.class);
                intent.putExtra("access_token", access_token);
                intent.putExtra("type", 10);//类型
                startActivity(intent);
                break;
            case R.id.iv_topic_share:
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_geren_main_share)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 600)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsBottom(v);
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {
            case R.layout.pop_geren_main_share:
                List<String> platformList = JShareInterface.getPlatformList();
                if (platformList == null || platformList.isEmpty()) {
                    ToolUtils.showToast(this, "请检查配置文件是否正确");
                    finish();
                    return;
                }
                ShareParams shareParams = new ShareParams();
                shareParams.setUrl("https://www.jiguang.cn");
                shareParams.setTargetPkg("com.tencent.mm");
                shareParams.setTargetClass("com.tencent.mm.ui.LauncherUI");
                shareParams.setExtra("this message from jshare.");
                LinearLayout ll_pop_cancel = view.findViewById(R.id.ll_pop_cancel);
                LinearLayout ll_pop_geren_haoyou = view.findViewById(R.id.ll_pop_geren_haoyou);
                LinearLayout ll_pop_geren_wx = view.findViewById(R.id.ll_pop_geren_wx);
                LinearLayout ll_pop_geren_pyq = view.findViewById(R.id.ll_pop_geren_pyq);
                LinearLayout ll_pop_geren_qq = view.findViewById(R.id.ll_pop_geren_qq);
                LinearLayout ll_pop_geren_wb = view.findViewById(R.id.ll_pop_geren_wb);
                ll_pop_geren_wx.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //只有微信支持表情
                        shareParams.setShareType(Platform.SHARE_EMOJI);
                        shareParams.setImagePath(MyApplication.ImagePath);
                        shareParams.setFilePath(MyApplication.ImagePath);
                        //只有微信支持文件
                        shareParams.setShareType(Platform.SHARE_FILE);
                        shareParams.setFilePath(MyApplication.ImagePath);
                        //只有微信支持小程序分享
//                        shareParams.setShareType(Platform.SHARE_MINI_PROGRAM);
//                        shareParams.setTitle("极光分享");
//                        shareParams.setText("分享");
//                        shareParams.setUrl("https://www.jiguang.cn");
//                        shareParams.setImagePath(MyApplication.ImagePath);
//                        shareParams.setMiniProgramWithShareTicket(false);//可以设置withShareTicket为true，当分享卡片在群聊中被其他用户打开时，可以获取到shareTicket
//                        shareParams.setMiniProgramType(0);// 正式版:0，开发版（测试版）:1，体验版（预览版）:2
//                        shareParams.setMiniProgramImagePath(MyApplication.ImagePath);//小程序图片地址
//                        shareParams.setMiniProgramPath("pages/index/index");//小程序页面路径
//                        shareParams.setMiniProgramUserName("gh_cd370c00d3d4");//小程序原始id·
                        JShareInterface.share(Wechat.Name, shareParams, mPlatActionListener);
                    }
                });
                ll_pop_geren_pyq.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //只有微信支持文件
                        shareParams.setShareType(Platform.SHARE_FILE);
                        JShareInterface.share(WechatMoments.Name, shareParams, mPlatActionListener);
                    }
                });
                ll_pop_geren_qq.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //只有支持QQ APP
                        shareParams.setShareType(Platform.SHARE_APPS);
                        shareParams.setImagePath(MyApplication.ImagePath);
                        JShareInterface.share(QQ.Name, shareParams, mPlatActionListener);
//                        JShareInterface.share(QZone.Name, shareParams, mPlatActionListener);//QQ空间
                    }
                });
                ll_pop_geren_wb.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        shareParams.setTitle("极光分享");
                        shareParams.setText("分享");
                        shareParams.setUrl("https://www.jiguang.cn");
                        shareParams.setShareType(Platform.SHARE_WEBPAGE);
                        shareParams.setImagePath(MyApplication.ImagePath);
                        JShareInterface.share(SinaWeiboMessage.Name, shareParams, mPlatActionListener);
                    }
                });
                ll_pop_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                    }
                });
//                shareParams.setShareType(Platform.SHARE_IMAGE);
//                shareParams.setImageUrl("");
//                JShareInterface.share("", shareParams, mPlatActionListener);
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求
     */
    private void postData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.gr_xyf_Url + access_token + "&limit=10", null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("xinyun", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                    } else {
                        ToolUtils.showToast(Topic_Detail_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(Topic_Detail_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }
}
